package cn.xzqwjw.taskmanager.security.handler;

import cn.xzqwjw.taskmanager.common.customEnum.ResponseCodeEnum;
import cn.xzqwjw.taskmanager.domain.vo.ResponseVo;
import cn.xzqwjw.taskmanager.utils.ResponseUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * NotLoginEntryPoint 用来解决未登录用户/匿名用户访问无权限资源时的异常
 * AuthAccessDeniedHandler 用来解决认证过的用户访问无权限资源时的异常
 */

/**
 * 自定义匿名用户访问无权限资源时错误输出格式，这里是输出成json
 *
 * @author rush
 */
@Component
public class NotLoginEntryPoint implements AuthenticationEntryPoint {

  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) {
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "没有凭证，需要登录！");
    ResponseUtil.writeJson(response, ResponseVo.error(ResponseCodeEnum.UNAUTHORIZED));
  }

}
